<template>
  <div class="search-container">
    <form action="/" style="position:fixed;width:100%;z-Index:99">
      <van-search
        v-model="searchValue"
        show-action
        background="#3296fa"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @input="valueChange"
        @focus="onFocus"
      />
    </form>
    <result v-if="showFlag" :resultVal="searchValue"></result>
    <suggestion v-else-if="searchValue.trim()" :searchVal="searchValue" @search="onSearch"></suggestion>
    <history v-else :historyVal="historyValue" @delALL="searchValue=[]" @search="onSearch"></history>
  </div>
</template>
<script>
import { SET_TOKEN, GET_TOKEN } from "@/utils/storage.js";
import history from "./components/search-history.vue";
import result from "./components/search-result.vue";
import suggestion from "./components/search-suggestion.vue";

export default {
  data() {
    return {
      searchValue: "",
      showFlag: false,
      historyValue: GET_TOKEN("history") || [],
    };
  },
  methods: {
    // 表单值发生变化时触发
    valueChange() {
      this.showFlag = false;
    },
    //  搜索
    onSearch(val) {
      this.searchValue = val;
      if (this.searchValue.trim().length == 0) {
        return;
      }
      var index = this.historyValue.findIndex((item) => {
        return item == val;
      });
      if (index != -1) {
        this.historyValue.splice(index, 1);
      }
      this.historyValue = [val, ...this.historyValue];
      // 把搜索历史记录在本地缓存保存
      SET_TOKEN("history", this.historyValue);
      // 点击搜索触发显示搜索结果
      // this.$toast(val);
      this.showFlag = true;
      this.value = "";
    },
    // 取消
    onCancel() {
      this.$toast("取消");
      // 点击取消返回到上一页
      this.$router.go(-1);
    },
    // 聚焦
    onFocus() {
      this.showFlag = false;
    },
  },
  components: {
    history,
    result,
    suggestion,
  },
};
</script>

<style lang="less">
.van-search__action {
  color: #fff;
}
/deep/.van-search .van-icon-search {
  margin-right: 0;
}
</style>
